package com.mqb;

import com.mqb.handler.ClientHandlersInitializer;
import com.mqb.quartz.ClientScheduler;
import com.mqb.session.MsgSession;
import com.mqb.util.ByteBufUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.time.LocalDateTime;
import java.util.Scanner;

public class Client {
    private static final Logger log = LoggerFactory.getLogger(Client.class);


    public static void main(String[] args) throws InterruptedException, SchedulerException {
        NioEventLoopGroup group = new NioEventLoopGroup();

        String userId = args[0];
        String destId = args[1];


        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ClientHandlersInitializer())
                .connect(new InetSocketAddress("localhost", 8080)).sync();

        log.info("connect to server success...");

        // 保存channel
        MsgSession.initServerChannel(channelFuture.channel());
        // 启动定时任务
        new ClientScheduler().startQuartz();

        // 建立成功后发送消息，表示此用户登陆了
        LoginEntity entity = new LoginEntity(userId, "pwd");
        LoginMsg loginMsg = new LoginMsg("0", userId, entity);
        channelFuture.channel().writeAndFlush(ByteBufUtil.transferWithHead(loginMsg));

        // 死循环客户端发送消息
        int i = 1;
        while (true) {
            Scanner scanner = new Scanner(System.in);
            String text = scanner.nextLine();
            RequestMsg requestMsg = new RequestMsg(
                    String.valueOf(i),
                    destId,
                    userId,
                    LocalDateTime.now(),
                    text);
            channelFuture.channel().writeAndFlush(ByteBufUtil.transferWithHead(requestMsg));

            MsgSession.add(requestMsg);
            i++;
            //ProcessingMsgQueue.push(String.valueOf(i++));
        }

    }
}



/*
//
//        try {
//            Channel channel = new Bootstrap()
//                    .group(group)
//                    .channel(NioSocketChannel.class)
//                    .handler(new ClientHandlersInitializer())
//                    .connect(new InetSocketAddress("localhost", 8080)).sync().channel();
//
//            channel.closeFuture().sync();
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            group.shutdownGracefully();
//        }
 */